package com.yuntongxun.ecdemo.ui.contact;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.yuntongxun.ecdemo.R;
import com.yuntongxun.ecdemo.common.CCPAppManager;
import com.yuntongxun.ecdemo.common.Events;
import com.yuntongxun.ecdemo.common.utils.LogUtil;
import com.yuntongxun.ecdemo.common.utils.ToastUtil;
import com.yuntongxun.ecdemo.core.ContactsCache;
import com.yuntongxun.ecdemo.rest.RetrofitUtil;
import com.yuntongxun.ecdemo.rest.interfaces.UserInterface;
import com.yuntongxun.ecdemo.rest.models.ServerResult;
import com.yuntongxun.ecdemo.rest.models.UserModel;
import com.yuntongxun.ecdemo.storage.ContactSqlManager;
import com.yuntongxun.ecdemo.ui.SDKCoreHelper;
import com.yuntongxun.ecsdk.ECChatManager;
import com.yuntongxun.ecsdk.ECDevice;
import com.yuntongxun.ecsdk.ECError;
import com.yuntongxun.ecsdk.PersonInfo;
import com.yuntongxun.ecsdk.SdkErrorCode;
import com.yuntongxun.ecsdk.platformtools.ECHandlerHelper;

import java.util.ArrayList;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by EVE on 2016/4/24.
 */
public class ContactsService {
    private static final String TAG  = "ECSDK_Demo.ContactService";

    private static ContactsService _instance;
    private boolean _isSync = false;

    private ContactsService() {
    }

    public static ContactsService getInstance() {
        if(_instance == null) {
            _instance = new ContactsService();
        }
        return _instance;
    }

    public void syncContacts() {
        if (SDKCoreHelper.getConnectState() != ECDevice.ECConnectState.CONNECT_SUCCESS) {
            return;
        }

        if(this._isSync) {
            LogUtil.d(TAG, "isSync is " + _isSync);
            return;
        }
        this._isSync = true;

        UserInterface retrieveContacts = RetrofitUtil.createRestApi(UserInterface.class);
        retrieveContacts.getContacts(CCPAppManager.getUserId(), new Callback<UserModel[]>() {
            @Override
            public void success(UserModel[] userModels, Response response) {

                if(userModels == null || userModels.length < 1) {
                    ContactsService.this._isSync = false;
                    return;
                }

                LogUtil.e("mylog.ContactsService", String.format("Sync %d contacts", userModels.length));

                ArrayList<String> deletingContacts = new ArrayList<String>();
                ArrayList<ECContacts> allContacts = ContactSqlManager.getAllContacts();

                for(UserModel user : userModels) {
                    ECContacts contact = ContactSqlManager.getContact(user.getAccount());
                    if (contact == null) {
                        contact = new ECContacts();
                        contact.setContactid(user.getAccount());
                    }
                    contact.setNickname(user.getName());
                    contact.setStatus(0);
                    ContactSqlManager.insertContact(contact);
                }

                for (ECContacts contact : allContacts) {
                    if(!containsAccount(contact, userModels)) {
                        deletingContacts.add(contact.getContactid());
                    }
                }

                ContactSqlManager.delete(deletingContacts);

                ContactsService.this._isSync = false;

                ContactsCache.getInstance().reload();
            }

            @Override
            public void failure(RetrofitError error) {
                if(error != null) {
                    LogUtil.e("mylog.ContactsService", "Failed to syncContacts, "
                            + error.getResponse().getStatus() + ","
                            + error.getResponse().getReason());
                    Response response = error.getResponse();
                    if(response.getStatus() == 401) {
                        try {
                            Context context = CCPAppManager.getContext();
                            if(context != null) {
                                context.sendBroadcast(new Intent(Events.UNAUTHORIZED));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                ContactsService.this._isSync = false;
            }
        });

    }

    private boolean containsAccount(ECContacts contact, UserModel[] users) {
        for(UserModel u : users) {
            if(u.getAccount().equals(contact.getContactid())) {
                return true;
            }
        }
        return false;
    }

    public void confirmFriend(final Context context, String contactId) {
        if (SDKCoreHelper.getConnectState() != ECDevice.ECConnectState.CONNECT_SUCCESS) {
            return;
        }

        String userId = CCPAppManager.getUserId();
        UserInterface usersInterface = RetrofitUtil.createRestApi(UserInterface.class);
        usersInterface.confirmFriend(userId, contactId, new Callback<ServerResult>() {
                    @Override
                    public void success(final ServerResult serverResult, Response response) {
                        if (serverResult.getErrno() == 0) {
                            syncContacts();
                        } else {
                            ToastUtil.showMessage(serverResult.getMsg());
                        }
                    }

                    @Override
                    public void failure(RetrofitError error) {
                        ToastUtil.showMessage(R.string.failed_to_add_friend);
                    }
                }
        );
    }

    public void deleteContact(final String contactId, final Runnable onSuccess, final Runnable onFailure) {
        if (SDKCoreHelper.getConnectState() != ECDevice.ECConnectState.CONNECT_SUCCESS) {
            return;
        }

        String userId = CCPAppManager.getUserId();
        UserInterface usersInterface = RetrofitUtil.createRestApi(UserInterface.class);
        usersInterface.deleteContact(userId, contactId, new Callback<ServerResult>() {
                    @Override
                    public void success(final ServerResult serverResult, Response response) {
                        ContactsCache.getInstance().delete(contactId);
                        if (serverResult != null && serverResult.getErrno() != 0) {
                            ToastUtil.showMessage(serverResult.getMsg());
                            if(onFailure != null) {
                                onFailure.run();
                            }
                        } else {
                            if (CCPAppManager.getContext() != null) {
                                CCPAppManager.getContext().sendBroadcast(new Intent(Events.CONTACTS_UPDATED));
                            }
                            if(onSuccess != null) {
                                onSuccess.run();
                            }
                        }
                    }

                    @Override
                    public void failure(RetrofitError error) {
                        ToastUtil.showMessage(R.string.failed_to_delete_friend);
                        if(onFailure != null) {
                            onFailure.run();
                        }
                    }
                }
        );
    }

    @Deprecated
    private void updateContacts() {
        if (SDKCoreHelper.getConnectState() != ECDevice.ECConnectState.CONNECT_SUCCESS) {
            return;
        }
        ECHandlerHelper handlerHelper = new ECHandlerHelper();
        handlerHelper.postDelayedRunnOnThead(new Runnable() {
            @Override
            public void run() {
                ArrayList<String> contactIds = ContactSqlManager.getNeedUpdateContactIds();
                for (String contact_id: contactIds) {
                    retrievePersonInfo(contact_id);
                }
            }
        }, 500);
    }

    @Deprecated
    private void retrievePersonInfo(String contact_id) {
        ECDevice.getPersonInfo(contact_id, new ECChatManager.OnGetPersonInfoListener() {
            @Override
            public void onGetPersonInfoComplete(ECError e, PersonInfo p) {
                if(SdkErrorCode.REQUEST_SUCCESS == e.errorCode) {
                    // 个人信息获取成功
                    // 更新个人信息到本地数据库，通知UI刷新
                    ECContacts contact = ContactSqlManager.getContact(p.getUserId());
                    if (contact == null) {
                        contact = new ECContacts();
                        contact.setContactid(p.getUserId());
                    }
                    contact.setNickname(p.getNickName());
                    ContactSqlManager.insertContact(contact);
                    ContactsCache.getInstance().reload();
                } else {
                    Log.e("ECSDK_Demo", "Failed to retrieve person info " +
                            ", errorCode=" + e.errorCode);
                }
            }
        });
    }

}
